package com.begamer.card.common.util.security.impl;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import com.begamer.card.common.util.security.IMessageDigest;

public class MessageDigestMD5Impl implements IMessageDigest {

	public String digest(String message) {
		if (message == null || message.length() == 0)
			return null;
		try {
			byte[] msg = message.getBytes();
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.reset();
			md.update(msg);
			byte[] results = md.digest();

			StringBuffer hexString = new StringBuffer();
			for (int i = 0; i < results.length; i++) {
				hexString.append(Integer.toHexString(0xFF & results[i]));
			}

			return hexString.toString();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public String encrypt(String message) {
		StringBuffer s = new StringBuffer();
		s.append("abc");

		if (message == null)
			return null;
		else
			message = message.substring(0, 1) + getRandomChar8()
					+ message.substring(1) + getRandomChar4();
		return (new BASE64Encoder()).encode(message.getBytes());
	}

	public String decryption(String message) {
		if (message == null)
			return null;

		BASE64Decoder decoder = new BASE64Decoder();
		try {
			byte[] b = decoder.decodeBuffer(message);
			String s = new String(b);
			s = s.substring(0, 1) + s.substring(9, s.length() - 4);
			return s;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	private String getRandomChar8() {
		Random r = new Random();
		int i = 0;
		int c;
		char[] b = new char[8];
		while (i < 8) {
			if ((c = r.nextInt(122)) > 64) {
				b[i] = (char) c;
				i++;
			}
		}
		return new String(b);

	}

	private String getRandomChar4() {
		Random r = new Random();
		int i = 0;
		int c;
		char[] b = new char[4];
		while (i < 4) {
			if ((c = r.nextInt(122)) > 64) {
				b[i] = (char) c;
				i++;
			}
		}
		return new String(b);

	}

}
